package com.woniuxy.ribbon.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 负载均衡规则定义类
 */
public class ClusterWeightRule extends AbstractLoadBalancerRule {
    /**
     * nacos信息对象
     */
    @Resource
    private NacosDiscoveryProperties ndp;
    /**
     * 服务注册查询等管理对象
     */
    @Resource
    private NacosServiceManager nsm;

    /**
     * 超时链接设置
     * @param iClientConfig
     */
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    /**
     * 自定义选择规则
     * @param o
     * @return
     */
    @Override
    public Server choose(Object o) {
        BaseLoadBalancer lb = (BaseLoadBalancer)getLoadBalancer();
        String serverName = lb.getName();
        String clusterName = ndp.getClusterName();
        String groupName = ndp.getGroup();
        NamingService ns = nsm.getNamingService(ndp.getNacosProperties());
        List<Instance> instances = null;
        try {
            instances = ns.selectInstances(serverName, groupName, true);
        } catch (NacosException e) {
            try {
                instances = ns.selectInstances(serverName, "DEFAULT_GROUP", true);
            } catch (NacosException ex) {
                throw new RuntimeException(ex);
            }
        }
        if (instances==null||instances.size()<=0){
            return null;
        }
        List<Instance> clusterInstances = instances.stream().filter(i -> i.getClusterName().equals(clusterName)).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(clusterInstances)){
            clusterInstances=instances;
        }
        Instance instance = RandomWeightRule.getRandomWeight(clusterInstances);
        return new NacosServer(instance);
    }

    /**
     * 随机选择规则
     */
    static class RandomWeightRule extends Balancer{
        public static Instance getRandomWeight(List<Instance> list){
            return Balancer.getHostByRandomWeight(list);
        }
    }
}
